<template>
  <el-dialog
      v-model="showModal"
      title="用户注册"
      :width="dialogWidth"
      :close-on-click-modal="false"
      :before-close="handleBeforeClose"
      @close="resetForm"
      custom-class="register-dialog"
  >
    <el-row class="register-container">
      <!-- 左侧二维码区域 -->
      <el-col :span="8" class="qr-code-section">
        <div class="qr-header">
          <h3>微信/QQ</h3>
          <p class="qr-subtitle">其他方式</p>
        </div>
        <div class="qr-placeholder">
          <!-- 可替换为真实二维码图片 -->
          <i class="el-icon-mobile-phone" style="font-size: 48px; color: #999;"></i>
        </div>
      </el-col>

      <!-- 右侧表单区域 -->
      <el-col :span="16" class="form-section">
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="formData.username"
                placeholder="请输入用户名"
                @input="handleUsernameInput"
            />
            <div class="validation-status">
              <span v-if="usernameChecking" style="color: #999; font-size: 12px;">检查中...</span>
              <span v-else-if="usernameError" style="color: red; font-size: 12px;">{{ usernameError }}</span>
              <i v-else-if="formData.username && usernameValid" class="el-icon-success" style="color: green;"></i>
            </div>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password" type="password" show-password placeholder="六位数字"/>
          </el-form-item>

          <!-- 确认密码 -->
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="formData.confirmPassword" type="password" show-password />
          </el-form-item>

          <!-- 手机号 -->
          <el-form-item label="手机号" prop="phone">
            <el-input
                v-model="formData.phone"
                placeholder="请输入手机号"
                @input="handlePhoneInput"
            />
            <div class="validation-status">
              <span v-if="phoneChecking" style="color: #999; font-size: 12px;">检查中...</span>
              <span v-else-if="phoneError" style="color: red; font-size: 12px;">{{ phoneError }}</span>
              <i v-else-if="formData.phone && phoneValid" class="el-icon-success" style="color: green;"></i>
            </div>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item label="验证码" prop="code">
            <el-input v-model="formData.code" style="width: 40%; display: inline-block;" />
            <el-button @click="sendVerificationCode" :disabled="sending" style="margin-left: 10px;">
              {{ sendText }}
            </el-button>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="agreedToTerms">
              我已阅读并同意
              <span class="terms-link" @click.stop="showTermsDialog = true">服务协议</span>
            </el-checkbox>

          </el-form-item>

          <!-- 按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm" style="width: 100%;">注册</el-button>
            <el-button @click="resetForm" style="width: 100%; margin-top: 10px;">重置</el-button>
          </el-form-item>
          <div class="service-register-link">
            <el-link @click="switchToLogin">已有账号？去登录</el-link>
          </div>

        </el-form>

        <!-- 注册为服务人员链接 -->
        <div class="service-register-link">
          <el-link type="primary" @click="goToServiceRegister">注册成为服务人员</el-link>
        </div>
      </el-col>
    </el-row>
  </el-dialog>

  <!-- 服务协议弹窗 -->
  <TermsDialog
      v-model="showTermsDialog"
      @agree="agreedToTerms = true"
  />

</template>

<script>
import _ from 'lodash';
import TermsDialog from '@/views/terms/TermsDialog.vue'; // 根据实际路径调整

// 👇 先定义函数，确保在 created 中可以使用
function getDialogWidth() {
  const width = window.innerWidth;
  if (width < 768) return '95%';     // 手机
  if (width < 992) return '80%';     // 平板
  return '40%';                      // PC
}
export default {
  name: "BaseUserRegister",
  components: {
    TermsDialog
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
  },


  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.formData.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    const validatePassword = (rule, value, callback) => {
      const regex = /^\d{6}$/;
      if (!regex.test(value)) {
        callback(new Error("密码必须是6位数字"));
      } else {
        callback();
      }
    };

    return {
      dialogWidth: '40%', // 初始值
      formData: {
        username: "",
        password: "",
        confirmPassword: "",
        phone: "",
        code: "",
        userType: 0,
      },
      sending: false,
      sendText: "获取验证码",
      agreedToTerms: false,
      showTermsDialog: false, // 控制服务协议弹窗显示
      // 用户名验证状态
      usernameValid: false,
      usernameChecking: false,
      usernameError: "",

      // 手机号验证状态
      phoneValid: false,
      phoneChecking: false,
      phoneError: "",

      // 防抖函数
      debouncedCheckUsername: null,
      debouncedCheckPhone: null,

      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    showModal: {
      get() {
        return this.modelValue;
      },
      set(value) {
        this.$emit("update:modelValue", value);
      },
    },
  },
  created() {
    this.dialogWidth = this.getDialogWidth(); // ✅ 放在这里
    this.debouncedCheckUsername = _.debounce(this.checkUsernameUnique, 500);
    this.debouncedCheckPhone = _.debounce(this.checkPhoneUnique, 500);
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    switchToLogin() {
      this.$emit('update:modelValue', false); // 关闭自己
      this.$emit('open-login'); // 触发 TopNav 切换
    },


    handleUsernameInput() {
      this.usernameChecking = true;
      this.usernameError = "";
      this.usernameValid = false;

      if (!this.validateUsernameFormat(this.formData.username)) {
        this.usernameChecking = false;
        this.usernameError = "用户名格式错误";
        return;
      }

      this.debouncedCheckUsername(this.formData.username);
    },

    handlePhoneInput() {
      this.phoneChecking = true;
      this.phoneError = "";
      this.phoneValid = false;

      if (!this.validatePhoneFormat(this.formData.phone)) {
        this.phoneChecking = false;
        this.phoneError = "手机号格式错误";
        return;
      }

      this.debouncedCheckPhone(this.formData.phone);
    },

    validateUsernameFormat(username) {
      if (!username) return false;
      const chineseRegex = /^[\u4e00-\u9fa5]{1,6}$/;
      const englishRegex = /^[a-zA-Z0-9]{1,10}$/;
      return chineseRegex.test(username) || englishRegex.test(username);
    },

    validatePhoneFormat(phone) {
      const regex = /^1[3-9]\d{9}$/;
      return regex.test(phone);
    },

    async checkUsernameUnique(username) {
      if (!username || !this.validateUsernameFormat(username)) return;

      try {
        const res = await fetch(`${BASE_URL}/api/v1/users/checkUsername?username=${username}`);
        const result = await res.json();

        if (res.ok && result.code === 2000) {
          if (result.data > 0) {
            this.usernameError = "该用户名已被占用";
          } else {
            this.usernameValid = true;
          }
        }
      } catch (err) {
        this.usernameError = "校验失败，请稍后再试";
      } finally {
        this.usernameChecking = false;
      }
    },

    async checkPhoneUnique(phone) {
      if (!phone || !this.validatePhoneFormat(phone)) return;

      try {
        const res = await fetch(`${BASE_URL}/api/v1/users/checkPhone?phone=${phone}`);
        const result = await res.json();

        if (res.ok && result.code === 2000) {
          if (result.data > 0) {
            this.phoneError = "该手机号已被占用";
          } else {
            this.phoneValid = true;
          }
        }
      } catch (err) {
        this.phoneError = "校验失败，请稍后再试";
      } finally {
        this.phoneChecking = false;
      }
    },

    async sendVerificationCode() {
      if (!this.formData.phone) {
        this.$message.warning("请先输入手机号");
        return;
      }

      this.sending = true;
      let timeLeft = 60;
      this.sendText = `${timeLeft}s`;

      const timer = setInterval(() => {
        if (timeLeft > 0) {
          timeLeft--;
          this.sendText = `${timeLeft}s`;
        } else {
          clearInterval(timer);
          this.sending = false;
          this.sendText = "获取验证码";
        }
      }, 1000);

      try {
        const response = await fetch(BASE_URL + "/api/v1/users/send-code", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ phone: this.formData.phone })
        });

        if (!response.ok) throw new Error("发送验证码失败");
        this.$message.success("验证码已发送，请查收短信");
      } catch (error) {
        this.$message.error("验证码发送失败，请重试");
        clearInterval(timer);
        this.sending = false;
        this.sendText = "获取验证码";
      }
    },

    submitForm() {
      if (!this.agreedToTerms) {
        this.$message.warning("请先同意服务协议");
        return;
      }
      if (!this.usernameValid && this.formData.username) {
        this.usernameError = "请完成用户名验证";
      }

      if (!this.phoneValid && this.formData.phone) {
        this.phoneError = "请完成手机号验证";
      }

      this.$refs.formRef.validate(async (valid) => {
        if (valid && this.usernameValid && this.phoneValid) {
          const { confirmPassword, ...submitData } = this.formData;

          try {
            const response = await fetch(BASE_URL + "/api/v1/users/register", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(submitData),
            });

            if (!response.ok) throw new Error("注册失败");

            const result = await response.json();
            const userData = result.data.user;
            const token = result.data.token;

            // 关键修复：确保设置 userType 为 0（新用户状态）
            userData.userType = 0; // 添加这行

            localStorage.setItem("user", JSON.stringify(userData));
            localStorage.setItem("token", token);


            this.$emit("register-success", { user: userData, token });
            this.showModal = false;
            this.resetForm();
            // this.$router.push("/index");
            // ✅ 修改：跳转到新手指引页
            this.$router.push("/guide");
          } catch (error) {
            this.$message.error("注册失败，请稍后再试");
          }
        } else {
          this.$message.error("请完成所有必填项验证");
        }
      });
    },

    resetForm() {
      this.usernameValid = false;
      this.usernameChecking = false;
      this.usernameError = "";
      this.phoneValid = false;
      this.phoneChecking = false;
      this.phoneError = "";
      this.agreedToTerms = false;

      this.$refs.formRef.resetFields();
      this.formData = {
        username: "",
        password: "",
        confirmPassword: "",
        phone: ""
      };
    },

    goToServiceRegister() {
      // 关闭当前注册弹窗
      this.showModal = false;
      // 延迟跳转确保弹窗关闭动画完成
      setTimeout(() => {
        this.$router.push('/register/service');
      }, 200);
    },

    handleBeforeClose(done) {
      this.$confirm('你确定退出注册吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
        this.resetForm();
      }).catch(() => {});
    },

      getDialogWidth() {
        const width = window.innerWidth;
        if (width < 768) return '95%';     // 手机
        if (width < 992) return '80%';     // 平板
        return '40%';                      // PC
      },
      handleResize() {
        this.dialogWidth = this.getDialogWidth();
      }


  },

};
</script>

<style lang="css" scoped>
@media (max-width: 768px) {
  .register-container {
    flex-direction: column;
  }

  .qr-code-section,
  .form-section {
    width: 100%;
    padding: 20px;
  }

  .qr-code-section {
    border-right: none;
    border-bottom: 1px solid #eee;
  }

  .service-register-link a {
    font-size: 13px;
  }
}

.register-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.register-container {
  background-color: #f9f9f9;
  padding: 0;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.qr-code-section {
  background-color: #fff;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 30px 20px;
  text-align: center;
  transition: background-color 0.3s ease;
}

.qr-code-section:hover {
  background-color: #f5f7fa;
}

.qr-header h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.qr-subtitle {
  font-size: 12px;
  color: #999;
  margin-bottom: 20px;
}

.qr-placeholder {
  width: 140px;
  height: 140px;
  background: #f0f0f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #aaa;
  font-size: 14px;
  border: 1px dashed #ddd;
  transition: border-color 0.3s ease;
}

.qr-placeholder:hover {
  border-color: #ff9800;
}

.form-section {
  padding: 30px 25px;
  background-color: #fff;
}

.validation-status {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  font-size: 12px;
}

.el-button--primary {
  background-color: #ff9800;
  border-color: #ff9800;
  transition: all 0.3s ease;
}

.el-button--primary:hover {
  background-color: #fb8c00;
  border-color: #fb8c00;
}

.service-register-link {
  text-align: center;
  margin-top: 15px;
}

.service-register-link a {
  font-size: 14px;
  color: #ff9800;
  transition: color 0.3s ease;
}

.service-register-link a:hover {
  color: #e65100;
}

/* 响应式支持 */
@media (max-width: 768px) {
  .register-container {
    flex-direction: column;
  }

  .qr-code-section,
  .form-section {
    width: 100%;
    padding: 20px;
  }

  .qr-code-section {
    border-right: none;
    border-bottom: 1px solid #eee;
  }
}
</style>
